import {takeEvery,put} from 'redux-saga/effects'
import axios from 'axios'
import {
  clear_todo_completed,clear_todo_completed_success, 
  load_todo,load_todo_success,add_todo,add_todo_success,
  remove_todo,remove_todo_success,
  modify_todo,modify_todo_success,
  modify_todo_edit,modify_todo__edit_success,
  modify_todo_name,modify_todo__name_success
} from '../actions/todo.actions'


// 实现方法获取数据
function* load_todo_data(){
 let todoData =  yield axios.get('/api/todos')
 //console.log(todoData)
 yield put(load_todo_success(todoData))
}

// 实现方法添加
function* add_todo_data(action){
  // 保存数据
  let taskInfo =  yield axios.post('/api/todos',{taskName:action.payload})
  // 发送请求
  yield put(add_todo_success(taskInfo.task))
}

// 实现删除
function* remove_todo_data(action){
  // 保存数据
  let res =  yield axios.delete('/api/todos',
    {
      params:{id:action.payload}
    })
  // 发送请求
  yield put(remove_todo_success(res.tasks.id))
}

// 是否选中
function* modify_todo_data(action){
  let params = action.payload
  let {task} = yield axios.put('/api/todos/isCompleted',params)
  yield put(modify_todo_success(task))
}

// 清空已完成
function* clear_todo_data(){
  // 删除后端数据
  yield axios.delete('/api/todos/clearCompleted')
  yield put(clear_todo_completed_success())
}

// 文本编辑框
function* modify_todo_edit_data(action){
  let params = action.payload
  yield axios.put('/api/todos/isEditing',params)
  yield put(modify_todo__edit_success(params))
}

// modify_todo_name_data
function* modify_todo_name_data(action){
  let params = action.payload
  yield axios.put('/api/todos',params)
  yield put(modify_todo__name_success(params))
}

// 发送请求
export default function* todoSage(){
  yield takeEvery(load_todo,load_todo_data)
  yield takeEvery(add_todo,add_todo_data)
  yield takeEvery(remove_todo,remove_todo_data)
  yield takeEvery(modify_todo,modify_todo_data)
  yield takeEvery(clear_todo_completed,clear_todo_data)
  yield takeEvery(modify_todo_edit,modify_todo_edit_data)
  yield takeEvery(modify_todo_name,modify_todo_name_data)
}
/***
 *  01-完成异步操作
 *  02-重新发送新的指令
 * 
 */